package com.example.spring.boot.rabbitmq.configuration;

import com.example.spring.boot.rabbitmq.constant.DeadLetterExchangeConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 死信队列配置类
 * </p>
 *
 * @author weixin
 * @date 2023/3/28 14:20
 */
@Configuration
public class DeadLetterExchangeConfig {

    /**
     * 定义队列参数
     */
    protected static final Map<String, Object> QUEUE_ARGUMENTS = new HashMap<>();

    static {
        // 设置队列最大长度
        QUEUE_ARGUMENTS.put("x-max-length", 10000);
        // 设置队列消息过期时间
        QUEUE_ARGUMENTS.put("x-message-ttl", 60000);
        // 设置队列死信交换机
        QUEUE_ARGUMENTS.put("x-dead-letter-exchange", DeadLetterExchangeConstant.DEAD_LETTER_EXCHANGE);
        // 设置队列死信路由键
        QUEUE_ARGUMENTS.put("x-dead-letter-routing-key", DeadLetterExchangeConstant.DEAD_LETTER_ROUTING_KEY);
    }

    @Bean
    public Queue deadLetterQueue() {
        return new Queue(DeadLetterExchangeConstant.DEAD_LETTER_QUEUE, true);
    }

    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(DeadLetterExchangeConstant.DEAD_LETTER_EXCHANGE);
    }

    @Bean
    public Binding deadLetterBinding(Queue deadLetterQueue, DirectExchange deadLetterExchange) {
        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange).with(DeadLetterExchangeConstant.DEAD_LETTER_QUEUE);
    }

}
